<!-- eslint-disable vue/valid-v-for -->
<template>
  <div class="main-container color">
    <a-row class="grid-demo" style="backgroundcolor: var(--color-fill-2)">
      <a-col :span="8" :offset="6">
        <a-form
          class="huakaClass"
          ref="mealRef"
          :model="mealForm"
          :auto-label-width="true"
          @submit="submitSetMeal"
        >
          <a-form-item label="充值方式" :content-flex="false" :merge-props="false">
            <a-row :gutter="24">
              <a-col :span="2">
                <a-radio style="margin-top: 10px" v-model="checked2" value="orderly" />
              </a-col>
              <a-col :span="10">
                <a-form-item
                  hide-asterisk
                  field="addCard"
                  validate-trigger="input"
                  :rules="[
                    {
                      required: checked2 == 'orderly' ? true : false,
                      message: '请输入开始卡号',
                    },
                  ]"
                  no-style
                  asterisk-position="end"
                >
                  <a-input
                    @blur="cardMealFn"
                    v-model="mealForm.addCard"
                    :disabled="checked2 == 'orderly' ? false : true"
                    placeholder="请输入开始卡号"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <div style="height: 1px; background-color: #000; margin-top: 16px"></div>
              </a-col>
              <a-col :span="10">
                <a-form-item
                  field="endCard"
                  hide-asterisk
                  validate-trigger="input"
                  :rules="[
                    {
                      required: checked2 == 'orderly' ? true : false,
                      message: '请输入结束卡号',
                    },
                  ]"
                  no-style
                  asterisk-position="end"
                >
                  <a-input
                    v-model="mealForm.endCard"
                    :disabled="checked2 == 'orderly' ? false : true"
                    placeholder="请输入结束卡号"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item
            field="cardMultiline"
            :content-flex="false"
            hide-asterisk
            :merge-props="false"
            :rules="[{ required: checked2 == 'disOrders' ? true : false, message: '卡号不能为空' }]"
            :validate-trigger="['change', 'input']"
            asterisk-position="end"
          >
            <a-row :gutter="24">
              <a-col :span="2">
                <a-radio style="margin-top: 10px" v-model="checked2" value="disOrders" />
              </a-col>
              <a-col :span="22">
                <a-textarea
                  :auto-size="{
                    minRows: 10,
                  }"
                  @blur="cardMealFns"
                  v-model="mealForm.cardMultiline"
                  :disabled="checked2 == 'disOrders' ? false : true"
                  placeholder="请输入卡号，一行一个"
                  allow-clear
                />
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item label="充值套餐" :content-flex="false" :merge-props="false">
            <a-row :gutter="24">
              <a-col :span="2" />
              <a-col :span="22">
                <a-form-item
                  hide-asterisk
                  field="setMealId"
                  validate-trigger="input"
                  :rules="[
                    {
                      required: checked1 == 'disOrder' ? false : true,
                      message: '请选择充值套餐',
                    },
                  ]"
                  no-style
                  asterisk-position="end"
                >
                  <a-select
                    @change="changeMeal"
                    v-model="mealForm.setMealId"
                    placeholder="请选择充值套餐"
                    allow-clear
                  >
                    <a-option v-for="item in mealList" :key="item.id" :value="item.id">{{
                      item.showName
                    }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item label="充值类型" :content-flex="false" :merge-props="false">
            <a-row :gutter="24">
              <a-col :span="2" />
              <a-col :span="22">
                <a-form-item
                  field="next"
                  hide-asterisk
                  validate-trigger="input"
                  :rules="[
                    {
                      required: true,
                      message: '请选择充值类型',
                    },
                  ]"
                  no-style
                  asterisk-position="end"
                >
                  <a-select v-model="mealForm.next" :disabled="lis" placeholder="请选择充值类型">
                    <a-option :value="0">本月</a-option>
                    <a-option :value="1">次月</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-item>
          <!-- <a-form-item label="提交上游" :content-flex="false" :merge-props="false">
            <a-row :gutter="24">
              <a-col :span="2" />
              <a-col :span="22">
                <a-form-item
                  field="upstream"
                  hide-asterisk
                  validate-trigger="input"
                  :rules="[
                    {
                      required: true,
                      message: '请选择是否提交上游',
                    },
                  ]"
                  no-style
                  asterisk-position="end"
                >
                  <a-select v-model="mealForm.upstream" placeholder="请选择是否提交上游">
                    <a-option :value="1">提交</a-option>
                    <a-option :value="0">不提交</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-item> -->
          <a-form-item
            field="remarks"
            label="充值备注"
            asterisk-position="end"
            :content-flex="false"
            :merge-props="false"
          >
            <a-row :gutter="24">
              <a-col :span="2" />
              <a-col :span="22">
                <a-input v-model="mealForm.remarks" placeholder="请输入充值备注" allow-clear />
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item :content-flex="false" :merge-props="false">
            <a-row :gutter="24">
              <a-col :span="2" />
              <a-col :span="22">
                <a-button html-type="submit" :loading="loadings" type="primary" class="width100"
                  >确认充值</a-button
                >
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item v-if="mealCardList.length > 0" :content-flex="false" :merge-props="false">
            <a-row :gutter="24">
              <a-col :span="2" />
              <a-col :span="22">
                <a-row style="margin-bottom: 10px">
                  <a-col :span="6"> 卡板数量:{{ mealCardList.length }} </a-col>
                  <a-col :span="6"> 成功数量:{{ zong.success }} </a-col>
                  <a-col :span="6"> 失败数量{{ zong.error }} </a-col>
                </a-row>
              </a-col>
              <a-col :span="2" />
              <a-col :span="22" style="margin-bottom: 10px">
                <a-progress
                  :show-text="false"
                  size="large"
                  :percent="(zong.success + zong.error) / mealCardList.length"
                />
              </a-col>
              <a-col :span="2" />
              <a-col :span="22">
                <div
                  style="
                    width: 100%;
                    height: 100px;
                    background-color: #f2f3f5;
                    overflow-y: scroll;
                    padding: 0 15px;
                  "
                >
                  <div v-for="item in errorList" :key="item">
                    {{ item }}
                  </div>
                </div>
              </a-col>
            </a-row>
          </a-form-item>
        </a-form>
        <!-- <a-divider type="dashed" :margin="20">常见问题</a-divider>
            <a-collapse>
              <a-collapse-item header="卡板充值的使用方法" key="1">
                <div
                  >下载充值模板，输入卡板ID，卡板ID在卡板列表第一列，然后输入要充值的卡号，导入充值充值文档，即可完成充值
                </div>
              </a-collapse-item>
            </a-collapse> -->
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
  import { getCardId, byCard, userMeal } from '@/api/user'
  import { post, formpost, get } from '@/api/http'
  import { Message } from '@arco-design/web-vue'
  import { onMounted, onUnmounted, ref } from 'vue'
  import useCommonStore from '@/store/modules/common'
  const useCommon = useCommonStore()
  const checked1: any = ref('orderly')
  const checked2: any = ref('orderly')

  const mealRef: any = ref()
  const mealList: any = ref()

  const loadings: any = ref(false)

  const setTimeOut = ref()
  const mealCardList: any = ref([])
  const zong = ref({
    success: 0,
    error: 0,
  })

  const mealForm: any = ref({
    addCard: '',
    endCard: '',
    cardMultiline: '',
    next: 0,
    setMealId: '',
    upstream: 1,
    remarks: '',
  })
  const count = ref(0)
  const errorList: any = ref([])
  const set: any = ref()
  function mealFn() {
    useCommon.usermealListFn().then((res) => {
      mealList.value = res.data
    })
  }
  function requestApi(item: any, card: any) {
    // 这里放置你的请求代码，item是列表中的元素
    const formData = new FormData()
    formData.append('remarks', set.value.remarks)
    formData.append('setMealId', set.value.setMealId)
    formData.append('next', set.value.next)
    formData.append('cardId', set.value.cardId)
    fetch(item, {
      method: 'POST',
      body: formData,
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.status == true) {
          zong.value.success++
        } else {
          zong.value.error++
        }
        errorList.value.unshift(card + ':' + (res.status == true ? res.data.outTradeNo : res.msg))
      })
      .catch((error) => console.log('Error:', error))
  }
  //获取卡板系列
  function cardMealFn() {
    mealList.value = []
    if (mealForm.value.addCard.length > 0) {
      get({
        url: byCard,
        data: () => {
          return {
            card: mealForm.value.addCard,
          }
        },
      })
        .then((res) => {
          if (res.code == 0) {
            console.log(res)
            get({
              url: userMeal,
              data: () => {
                return {
                  seriesIds: res.data.seriesId,
                }
              },
            }).then((res) => {
              if (res.code == 0) {
                mealList.value = res.data
              }
            })
          }
        })
        .catch(() => {})
    }
  }
  //获取卡板系列
  function cardMealFns() {
    mealList.value = []
    let aap = mealForm.value.cardMultiline.split(/[(\r\n)\r\n]+/)
    if (mealForm.value.cardMultiline.length > 0) {
      get({
        url: byCard,
        data: () => {
          return {
            card: aap[0],
          }
        },
      })
        .then((res) => {
          if (res.code == 0) {
            console.log(res)
            get({
              url: userMeal,
              data: () => {
                return {
                  seriesIds: res.data.seriesId,
                }
              },
            }).then((res) => {
              if (res.code == 0) {
                mealList.value = res.data
              }
            })
          }
        })
        .catch(() => {})
    }
  }
  const lis = ref(false)
  function changeMeal(val: any) {
    mealList.value.forEach((item: any) => {
      console.log('进来了')
      if (item.id == val) {
        if (item.next) {
          lis.value = false
        } else {
          lis.value = true
        }
        mealForm.value.next = 0
      }
    })
  }
  // 充值套餐
  const submitSetMeal = () => {
    mealRef.value?.validate().then((error: any) => {
      if (!error) {
        mealCardList.value = []
        zong.value = {
          success: 0,
          error: 0,
        }
        errorList.value = []
        count.value = 0
        set.value = JSON.parse(JSON.stringify(mealForm.value))
        if (checked2.value == 'orderly') {
          formpost({
            url: getCardId,
            data: () => {
              return {
                addCard: mealForm.value.addCard,
                endCard: mealForm.value.endCard,
              }
            },
          })
            .then((res) => {
              if (res.code == 0) {
                mealCardList.value = res.data
                setTimeOut.value = setInterval(() => {
                  if (count.value < mealCardList.value.length) {
                    // 请求接口
                    set.value.cardId = mealCardList.value[count.value].id
                    requestApi(`/app/user/order/pay`, mealCardList.value[count.value].card)
                    count.value++ // 增加计数器
                  } else {
                    // 请求次数达到列表长度，清除定时器并停止
                    clearInterval(setTimeOut.value)
                  }
                }, 3000)
              }
            })
            .catch(() => {})
        } else if (checked2.value == 'disOrders') {
          formpost({
            url: getCardId,
            data: () => {
              return {
                cards: mealForm.value.cardMultiline.split(/\n/g).join(','),
              }
            },
          })
            .then((res) => {
              if (res.code == 0) {
                mealCardList.value = res.data
                setTimeOut.value = setInterval(() => {
                  if (count.value < mealCardList.value.length) {
                    set.value.cardId = mealCardList.value[count.value].id
                    // 请求接口
                    requestApi(`/app/user/order/pay`, mealCardList.value[count.value].card)
                    count.value++ // 增加计数器
                  } else {
                    // 请求次数达到列表长度，清除定时器并停止
                    clearInterval(setTimeOut.value)
                  }
                }, 3000)
              }
            })
            .catch(() => {})
        }
      }
    })
  }

  import { onBeforeRouteLeave } from 'vue-router'

  onBeforeRouteLeave((to, from, next) => {
    //清除定时器
    clearInterval(setTimeOut.value) // 组件销毁时清除定时器
    next()
  })

  onMounted(async () => {
    await mealFn()
  })
</script>

<style scoped>
  .color {
    background-color: var(--color-bg-1);
    border-radius: 10px;
    padding: 20px;
  }

  :deep(.arco-upload) {
    width: 100%;
  }

  .arco-radio-group :deep(.arco-radio) {
    margin-right: 0px;
  }
  .huakaClass {
    padding: 30px 0px;
  }
  .huakaClass :deep(.arco-form-item-message) {
    margin-left: 42px !important;
  }
  .huakaClass :deep(.arco-upload-progress) {
    display: none !important;
  }
</style>
